package com.yj.suncity.publish;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.bean.AlreadyAdvBean;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;

@SuppressLint("NewApi")
public class PublishAdvertiseActivity extends Activity implements
		OnClickListener {
	private Uri photoUri;// 照片路径
	private final int PIC_FROM_CAMERA = 0x10086;// 拍照
	private final int PIC_FROM_IMAGE = 0x10088;// 从本地选择图片
	private final int PIC_FROM_ZOOM = 0x10087;
//	private static final String IMAGE_FILE_NAME = "face.jpg";  
	private String photoName = "";
    /* 请求码 */  
    private static final int IMAGE_REQUEST_CODE = 0;  
    private static final int SELECT_PIC_KITKAT = 3;  
    private static final int CAMERA_REQUEST_CODE = 1;  
    private static final int RESULT_REQUEST_CODE = 2; 

	private Context context;
	private String userId;
	private String titleName;
	private EditText mEdt_title, mEdt_amount, mEdt_num, mEdt_xjsm, mEdt_dzsm,
			mEdt_zssm, mEdt_yhsm, mEdt_djqsm, mEdt_copies;
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();

	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private String picPath;// 拍照后保存图片的路径
	private ProgressUtil progressUtil;
	private ArrayList<String> uploadPaths = new ArrayList<String>();
	private Button mBtn_add_img;
	private RelativeLayout mLay_rela_img;
	private TextView mTxt_img_num;
	private String img_result;
	// private boolean isSelectImg;
	private ImageView mImg_all_logo;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "" + (String) msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "上传成功！");
				PublishAdvertiseActivity.this.finish();
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish_advertse);
		context = this;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		userId = getIntent().getStringExtra("userid");
		titleName = getIntent().getStringExtra("titlename");
		if (titleName == null) {
			titleName = "发布广告";
			findView();
		} else {
			findView();
			initData();
		}
	}

	private void initData() {
		String path = URLCon.广告 + "?action=seeentadv&userid=" + userId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						AlreadyAdvBean advBean = new AlreadyAdvBean(jsonObject);
						img_result = advBean.getAdv_img();
						mEdt_title.setText(advBean.getTitle());
						mEdt_num.setText(advBean.getNum());
						mEdt_amount.setText(advBean.getAmount());
						mEdt_xjsm.setText(advBean.getXj_content());
						mEdt_dzsm.setText(advBean.getDz_content());
						mEdt_zssm.setText(advBean.getZs_content());
						mEdt_yhsm.setText(advBean.getYh_content());
						mEdt_djqsm.setText(advBean.getDjq_content());
						mEdt_copies.setText(advBean.getCopies());
						if (!img_result.equals("")) {
							uploadPaths.add(img_result);
							setAdapter();
						}
					}
				});
		asyncTaskUtil.execute(path);

	}

	private void findView() {
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);
		mEdt_title = (EditText) findViewById(R.id.edt_seeadv_title);
		mEdt_amount = (EditText) findViewById(R.id.edt_seeadv_amount);
		mEdt_num = (EditText) findViewById(R.id.edt_seeadv_num);
		mEdt_xjsm = (EditText) findViewById(R.id.edt_seeadv_xjsm);
		mEdt_dzsm = (EditText) findViewById(R.id.edt_seeadv_dzsm);
		mEdt_zssm = (EditText) findViewById(R.id.edt_seeadv_zssm);
		mEdt_yhsm = (EditText) findViewById(R.id.edt_seeadv_yhsm);
		mEdt_djqsm = (EditText) findViewById(R.id.edt_seeadv_djqsm);
		mEdt_copies = (EditText) findViewById(R.id.edt_copies);

		mBtn_add_img = (Button) findViewById(R.id.btn_add_img);
		mBtn_add_img.setOnClickListener(this);
		mLay_rela_img = (RelativeLayout) findViewById(R.id.lay_rela_img);
		mTxt_img_num = (TextView) findViewById(R.id.txt_img_num);
		mImg_all_logo = (ImageView) findViewById(R.id.img_all_logo);
		mImg_all_logo.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_ok:
			String title = mEdt_title.getText().toString().trim();
			String amount = mEdt_amount.getText().toString().trim();
			String num = mEdt_num.getText().toString().trim();
			String xjsm = mEdt_xjsm.getText().toString().trim();
			String dzsm = mEdt_dzsm.getText().toString().trim();
			String zssm = mEdt_zssm.getText().toString().trim();
			String yhsm = mEdt_yhsm.getText().toString().trim();
			String djqsm = mEdt_djqsm.getText().toString().trim();
			String copies = mEdt_copies.getText().toString().trim();

			if (uploadPaths.size() <= 0) {
				ToastUtil.ShowToast(context, "请选择图片！");
				return;
			}

			if (title.equals("")) {
				ToastUtil.ShowToast(context, "请设定广告语！");
				return;
			}
			if (amount.equals("")) {
				ToastUtil.ShowToast(context, "请设定看广告总金额！");
				return;
			}
			if (num.equals("")) {
				ToastUtil.ShowToast(context, "请设定看广告人数！");
				return;
			}
			if (xjsm.equals("")) {
				ToastUtil.ShowToast(context, "请设定现金！");
				return;
			}
			// if (dzsm.equals("")) {
			// ToastUtil.ShowToast(context, "请设定打折说明！");
			// return;
			// }
			// if (zssm.equals("")) {
			// ToastUtil.ShowToast(context, "请设定赠送说明！");
			// return;
			// }
			// if (yhsm.equals("")) {
			// ToastUtil.ShowToast(context, "请设定优惠说明！");
			// return;
			// }
			// if (djqsm.equals("")) {
			// ToastUtil.ShowToast(context, "请选择图片！");
			// return;
			// }
			if (copies.equals("")) {
				ToastUtil.ShowToast(context, "请设定份数！");
				return;
			}

			int id = Integer.parseInt(amount);
			if (id <= 0) {
				ToastUtil.ShowToast(context, "红包总金额不能少于0");
				return;
			}
			if (((String) this.uploadPaths.get(0)).contains(ShareCon.SD)) {
				uploadImg(title, amount, num, xjsm, dzsm, zssm, yhsm, djqsm,
						copies);
			} else {
				stringBuffer.append(uploadPaths.get(0));
				progressUtil = new ProgressUtil();
				progressUtil.ShowProgress(context, true, false, "正在上传......");
				publishADV(title, amount, num, xjsm, dzsm, zssm, yhsm, djqsm,
						copies);
			}
			break;

		case R.id.btn_add_img:// 添加图片按钮
			popView();
			break;
		case R.id.img_all_logo:// 点击图片查看
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("paths", uploadPaths);
			bundle.putInt("posi", 0);
			// bundle.putBoolean("selectimg", isSelectImg);
			Intent intent = new Intent(context, SelectPicShowActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, 103);
			break;
		}
	}

	/**
	 * 重置图片布局
	 */
	private void setAdapter() {
		// mPublish_img_gallery.setAdapter(new PublishGalleryAdapter(context,
		// uploadPaths));
		// if (uploadPaths.size() > 0) {
		// mPublish_img_gallery.setSelection(1);
		// }
		if (uploadPaths.size() == 1) {
			mBtn_add_img.setVisibility(View.GONE);
			mLay_rela_img.setVisibility(View.VISIBLE);
			mTxt_img_num.setText(String.valueOf(uploadPaths.size()));
			if (((String) this.uploadPaths.get(0)).contains(ShareCon.SD)) {
				imageLoader.displayImage("file://" + uploadPaths.get(0),
						mImg_all_logo, options);
			} else {
				imageLoader.displayImage(URLCon.HOST + uploadPaths.get(0),
						mImg_all_logo, options);
			}
		} else {
			mBtn_add_img.setVisibility(View.VISIBLE);
			mLay_rela_img.setVisibility(View.GONE);
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		if (uri == null) {  
            Log.i("tag", "The uri is not exist.");  
            return;  
        }  
          
        Intent intent = new Intent("com.android.camera.action.CROP");  
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {  
            String url=getPath(context,uri);  
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");  
        }else{  
            intent.setDataAndType(uri, "image/*");  
        }  
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 9);
		intent.putExtra("aspectY", 16);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 180);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	private StringBuffer stringBuffer = new StringBuffer();

	private void uploadImg(final String title, final String amount,
			final String num, final String xjsm, final String dzsm,
			final String zssm, final String yhsm, final String djqsm,
			final String copies) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("action", "uploads");
		UploadUtil uploadUtil = new UploadUtil();
		progressUtil = new ProgressUtil();
		progressUtil.ShowProgress(context, true, false, "正在上传......");
		uploadUtil.uploadFile(context, uploadPaths, "txtimg", URLCon.图片上传,
				param, new OnUploadProcessListener() {
					@Override
					public void UploadResule(String result) {
						Log.d("", "result===" + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							if (jsonObject.optString("success").equals("1")) {
								JSONArray array = jsonObject
										.optJSONArray("data");
								stringBuffer.delete(0, stringBuffer.length());
								for (int i = 0; i < array.length(); i++) {
									String url = array.optJSONObject(i)
											.optString("url");
									stringBuffer.append(url + ",");
								}
								stringBuffer.deleteCharAt(stringBuffer.length() - 1);
								publishADV(title, amount, num, xjsm, dzsm,
										zssm, yhsm, djqsm, copies);
							} else {
								Message message = new Message();
								message.what = FAIL;
								message.obj = jsonObject.optString("msg");
								handler.sendMessage(message);
							}
						} catch (JSONException e) {
							Message message = new Message();
							message.what = JSON_EXCEPTION;
							handler.sendMessage(message);
							e.printStackTrace();
						}
					}
				});
	}

	private void publishADV(String title, String amount, String num,
			String xjsm, String dzsm, String zssm, String yhsm, String djqsm,
			String copies) {
		pairs.clear();
		final String path = URLCon.广告;
		pairs.add(new BasicNameValuePair("action", "publishadv"));
		pairs.add(new BasicNameValuePair("userid", userId));
		pairs.add(new BasicNameValuePair("title", title));
		pairs.add(new BasicNameValuePair("amount", amount));
		pairs.add(new BasicNameValuePair("num", num));
		pairs.add(new BasicNameValuePair("xjsm", xjsm));
		pairs.add(new BasicNameValuePair("dzsm", dzsm));
		pairs.add(new BasicNameValuePair("zssm", zssm));
		pairs.add(new BasicNameValuePair("yhsm", yhsm));
		pairs.add(new BasicNameValuePair("djqsm", djqsm));
		pairs.add(new BasicNameValuePair("copies", copies));
		pairs.add(new BasicNameValuePair("img", stringBuffer.toString()));

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					JSONObject jsonObject = new JSONObject(json);
					Message message = new Message();
					if (jsonObject.optString("success").equals("1")) {
						message.what = SUCCESS;
					} else {
						message.what = FAIL;
					}
					message.obj = jsonObject.optString("msg");
					handler.sendMessage(message);

				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread = null;
	}

	private void popView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {// 拍照
					 Intent intentFromCapture = new Intent(  
                             MediaStore.ACTION_IMAGE_CAPTURE);  
                     // 判断存储卡是否可以用，可用进行存储  
                     if (hasSdcard()) {  
                    	 photoName = getPhotoFileName();
                         intentFromCapture.putExtra(  
                                 MediaStore.EXTRA_OUTPUT,  
                                 Uri.fromFile(new File(Environment  
                                         .getExternalStorageDirectory(),  
                                         photoName)));  
                     }else {  
                         ToastUtil.ShowToast(context,"未找到存储卡，无法存储照片！");  
                     }  
                     startActivityForResult(intentFromCapture,  
                             CAMERA_REQUEST_CODE);
//					doHandlerPhoto(PIC_FROM_CAMERA);
				} else if (index == 1) {// 相册
					Intent intent=new Intent(Intent.ACTION_GET_CONTENT);  
                    intent.addCategory(Intent.CATEGORY_OPENABLE);  
                    intent.setType("image/*");  
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {  
                        startActivityForResult(intent,SELECT_PIC_KITKAT);  
                    } else {  
                        startActivityForResult(intent,IMAGE_REQUEST_CODE);  
                    }  
				}
			}
		});
	}
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_CANCELED) {  
            switch (requestCode) {  
            case IMAGE_REQUEST_CODE:  
                startPhotoZoom(data.getData());  
                break;  
            case SELECT_PIC_KITKAT:  
                startPhotoZoom(data.getData());  
                break;  
            case CAMERA_REQUEST_CODE:  
                if (hasSdcard()) {  
                    File tempFile = new File(Environment.getExternalStorageDirectory(),photoName);  
                    startPhotoZoom(Uri.fromFile(tempFile));  
                } else {  
                    ToastUtil.ShowToast(context,"未找到存储卡，无法存储照片！");  
                }  

                break;  
            case RESULT_REQUEST_CODE:  
                if (data != null) {  
                	setImageToView(data);
                	
                	File file = new File(Environment.getExternalStorageDirectory(),photoName);  
                	picPath=file.getAbsolutePath();
        			if (BitmapFactory.decodeFile(picPath) == null) {
        				break;
        			}
        			uploadPaths.clear();
        			uploadPaths.add(picPath);
        			 setAdapter();
                }  
                break;  
            }  
        } 
//		switch (requestCode) {
//		case PIC_FROM_IMAGE:// 从本地选择照片
//			if (photoUri == null) {
//				break;
//			}
//			picPath = photoUri.toString().replace("file://", "");
//			if (BitmapFactory.decodeFile(picPath) == null) {
//				break;
//			}
//			uploadPaths.clear();
//			uploadPaths.add(picPath);
//			 setAdapter();
//			break;
//		case PIC_FROM_CAMERA: // 拍照选择相片
//			try {
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			break;
//		case PIC_FROM_ZOOM:
//			break;
//		}
//		setAdapter();

		// 查看选择的图片后返回的数据
		if (requestCode == 103 && resultCode == 103) {
			List<String> paths = data.getStringArrayListExtra("picPaths");
			// isSelectImg = data.getBooleanExtra("selectimg", true);
			if (paths != null && paths.size() > 0) {
				// imaLayout.removeAllViews();
				uploadPaths.clear();
				uploadPaths.addAll(paths);
				// 利用HashSet过滤掉一样的路径
				HashSet<String> set = new HashSet<String>(uploadPaths);
				uploadPaths.clear();
				uploadPaths.addAll(set);

				setAdapter();
			}
		}
		// 查看选择的图片后返回的数据
		if (requestCode == 103 && resultCode == 104) {
			uploadPaths.clear();
			setAdapter();
		}
		//
		// // 选择本地图库图片后返回的数据
		// if (requestCode == 103 && resultCode == 105) {
		// isSelectImg = data.getBooleanExtra("selectimg", true);
		// List<String> paths = data.getStringArrayListExtra("picPaths");
		// if (paths != null && paths.size() > 0) {
		// // imaLayout.removeAllViews();
		// uploadPaths.addAll(paths);
		// // 利用HashSet过滤掉一样的路径
		// HashSet<String> set = new HashSet<String>(uploadPaths);
		// uploadPaths.clear();
		// uploadPaths.addAll(set);
		// if (uploadPaths.size() > 1) {
		// uploadPaths.removeAll(paths);
		// ToastUtil.ShowToast(context, "您最多可以选择1张图片！");
		// return;
		// }
		// File tempFile = new File(uploadPaths.get(0));
		// startPhotoZoom(Uri.fromFile(tempFile));
		// // setAdapter();
		// }
		// }
		super.onActivityResult(requestCode, resultCode, data);
	}
	/**  
     * 保存裁剪之后的图片数据  
     *   
     * @param picdata  
     */  
    private void setImageToView(Intent data) {  
        Bundle extras = data.getExtras();  
        if (extras != null) {  
            Bitmap photo = extras.getParcelable("data");  
            saveBitmap(photo);  
        }  
    }  

    public void saveBitmap(Bitmap mBitmap) {  
    	if("".equals(photoName) || photoName == null){
    		photoName = getPhotoFileName();
    	}
        File f = new File(Environment.getExternalStorageDirectory(),photoName);  
        try {  
            f.createNewFile();  
            FileOutputStream fOut = null;  
            fOut = new FileOutputStream(f);  
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);  
            fOut.flush();  
            fOut.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}
	 //以下是关键，原本uri返回的是file:///...来着的，android4.4返回的是content:///...  
    @SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {  

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  

        // DocumentProvider  
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  
            // ExternalStorageProvider  
            if (isExternalStorageDocument(uri)) {  
                final String docId = DocumentsContract.getDocumentId(uri);  
                final String[] split = docId.split(":");  
                final String type = split[0];  

                if ("primary".equalsIgnoreCase(type)) {  
                    return Environment.getExternalStorageDirectory() + "/" + split[1];  
                }  

            }  
            // DownloadsProvider  
            else if (isDownloadsDocument(uri)) {  
                final String id = DocumentsContract.getDocumentId(uri);  
                final Uri contentUri = ContentUris.withAppendedId(  
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));  

                return getDataColumn(context, contentUri, null, null);  
            }  
            // MediaProvider  
            else if (isMediaDocument(uri)) {  
                final String docId = DocumentsContract.getDocumentId(uri);  
                final String[] split = docId.split(":");  
                final String type = split[0];  

                Uri contentUri = null;  
                if ("image".equals(type)) {  
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
                } else if ("video".equals(type)) {  
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
                } else if ("audio".equals(type)) {  
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
                }  

                final String selection = "_id=?";  
                final String[] selectionArgs = new String[] {  
                        split[1]  
                };  

                return getDataColumn(context, contentUri, selection, selectionArgs);  
            }  
        }  
        // MediaStore (and general)  
        else if ("content".equalsIgnoreCase(uri.getScheme())) {  
            // Return the remote address  
            if (isGooglePhotosUri(uri))  
                return uri.getLastPathSegment();  

            return getDataColumn(context, uri, null, null);  
        }  
        // File  
        else if ("file".equalsIgnoreCase(uri.getScheme())) {  
            return uri.getPath();  
        }  

        return null;  
    }  

    /** 
     * Get the value of the data column for this Uri. This is useful for 
     * MediaStore Uris, and other file-based ContentProviders. 
     * 
     * @param context The context. 
     * @param uri The Uri to query. 
     * @param selection (Optional) Filter used in the query. 
     * @param selectionArgs (Optional) Selection arguments used in the query. 
     * @return The value of the _data column, which is typically a file path. 
     */  
    public static String getDataColumn(Context context, Uri uri, String selection,  
            String[] selectionArgs) {  

        Cursor cursor = null;  
        final String column = "_data";  
        final String[] projection = {  
                column  
        };  

        try {  
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,  
                    null);  
            if (cursor != null && cursor.moveToFirst()) {  
                final int index = cursor.getColumnIndexOrThrow(column);  
                return cursor.getString(index);  
            }  
        } finally {  
            if (cursor != null)  
                cursor.close();  
        }  
        return null;  
    }  


    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is ExternalStorageProvider. 
     */  
    public static boolean isExternalStorageDocument(Uri uri) {  
        return "com.android.externalstorage.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is DownloadsProvider. 
     */  
    public static boolean isDownloadsDocument(Uri uri) {  
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is MediaProvider. 
     */  
    public static boolean isMediaDocument(Uri uri) {  
        return "com.android.providers.media.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is Google Photos. 
     */  
    public static boolean isGooglePhotosUri(Uri uri) {  
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());  
    } 
}
